package com.wanrue.tcc.commom;

import com.wanrue.tcc.common.ContextService;
import com.wanrue.tcc.context.Context;
import com.wanrue.tcc.context.Invocation;
import com.wanrue.tcc.exception.SystemException;
import com.wanrue.tcc.support.FactoryBuilder;
import com.wanrue.tcc.utils.StringUtils;

import java.io.Serializable;
import java.lang.reflect.Method;

/**
 * 事务参与者 执行器
 * Created by changmingxie on 10/30/15.
 */
public class Invoker implements Serializable {

    private static final long serialVersionUID = -164958655471605778L;

    public static void invoke(Context context, Invocation invocation) {
        String methodName = invocation.getMethod();
        if (StringUtils.isNotEmpty(methodName)) {
            try {
                Method method = invocation.getTarget().getMethod(methodName, invocation.getParameterTypes());
                Object target = FactoryBuilder.factoryOf(invocation.getTarget()).getInstance();
                FactoryBuilder.factoryOf(ContextService.class).getInstance().set(context, method, invocation.getArgs());
                method.invoke(target, invocation.getArgs());
            } catch (Exception e) {
                throw new SystemException(e);
            }
        }
    }
}
